package com.android.infantschool.ui.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.android.infantschool.R;
import com.android.infantschool.bean.BabyParentsBean;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.QiNiuTokenBean;
import com.android.infantschool.bean.ReleaseDynamicBean;
import com.android.infantschool.bean.ResponseBean;
import com.android.infantschool.event.BabyParentsEvent;
import com.android.infantschool.manager.ThreadPoolManager;
import com.android.infantschool.model.config.AppCommand;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.config.AppDataSource;
import com.android.infantschool.model.http.OkHttpUtil;
import com.android.infantschool.model.mvp.presenter.BabyParentsPresenter;
import com.android.infantschool.model.mvp.presenter.BabyParentsPresenterImpl;
import com.android.infantschool.model.mvp.presenter.InfromPresenter;
import com.android.infantschool.model.mvp.presenter.InfromPresenterImpl;
import com.android.infantschool.model.mvp.view.BabyParentsView;
import com.android.infantschool.model.mvp.view.InfromView;
import com.android.infantschool.model.qiniu.QnUploadHelper;
import com.android.infantschool.ui.adapter.ReleaseDynamicAdapter;
import com.android.infantschool.util.DateUtil;
import com.android.infantschool.util.JsonGet;
import com.android.infantschool.util.ScreenUtil;
import com.android.infantschool.util.ToastUtil;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.qiniu.android.http.ResponseInfo;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\5 0005 15:52
 * @class describe
 */
public class VoteInfromActivity extends BaseActivity implements ReleaseDynamicAdapter.OnImgLister, InfromView, BabyParentsView {

    @BindView(R.id.img_back)
    public ImageView imgBack;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.ed_content)
    public EditText edContent;
    @BindView(R.id.tv_content_size)
    public TextView tvContentSize;
    @BindView(R.id.recyclerView)
    public RecyclerView recyclerView;
    @BindView(R.id.btn_release)
    public Button btnRelease;

    public ReleaseDynamicAdapter adapter;

    @BindView(R.id.ed_title)
    public EditText edTitle;
    @BindView(R.id.tv_select_name)
    public TextView tvSelectName;

    private StringBuilder stringBuilder = new StringBuilder();
    private int REQUEST_GET_IMAGE = 1;
    //存放图片或视频路径的ArrayList
    private int picNum = 0;                 //当前上传到多少张
    private boolean flag = true;            //true:上传中,false:上传成功

    private InfromPresenter presenter = null;
    private BabyParentsPresenter parentsPresenter = null;

    public static Intent newIntent(Activity activity) {
        Intent intent = new Intent(activity, VoteInfromActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_infrom_vote);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        parentsPresenter = new BabyParentsPresenterImpl(this);
        presenter = new InfromPresenterImpl(this);
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText("私信");

        adapter = new ReleaseDynamicAdapter(this, this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5) {
            @Override
            public boolean canScrollVertically() {
                return false;//禁止滑动
            }
        };

        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setData(AppDataSource.getReleaseDynamicList());
        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                length = 500 - length;
                tvContentSize.setText(length + "/500");
            }
        });
    }

    @OnClick({R.id.btn_release, R.id.img_back, R.id.tv_select_name})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_release:
                String title = edTitle.getText().toString().trim();
                String content = edContent.getText().toString().trim();
                if (TextUtils.isEmpty(title)) {
                    ToastUtil.showShortToast(this, "请输入标题");
                    return;
                }
                if (TextUtils.isEmpty(content)) {
                    ToastUtil.showShortToast(this, "请输入叮嘱内容");
                    return;
                }

                if (babyMap.size() < 1) {
                    ToastUtil.showShortToast(this, "请选择宝宝家长");
                    return;
                }

                if (adapter.list.size() < 2) {
                    ToastUtil.showShortToast(this, "请选择图片");
                    return;
                }

                if (babyMap.size() < 1 || TextUtils.isEmpty(tvSelectName.getText().toString())) {
                    ToastUtil.showShortToast(this, "请选择宝宝家长");
                    return;
                }

                stringBuilder.delete(0, stringBuilder.toString().length());
                this.showLoading();
                if (flag == true) {
                    this.showLoading();
                    qiuNiuYunToKen((String) adapter.list.get(picNum).path, adapter.getItemCount() - 1);
                    flag = false;
                } else {
                    Toast.makeText(this, "正在上传，请稍后...", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.img_back:
                this.finish();
                break;
            case R.id.tv_select_name:
                Map<String, String> map = new HashMap<>();
                map.put("bindingStatus", "1");
                map.put("token", AppConfig.getToken());
                Log.e(TAG, "map:" + map.toString());
                parentsPresenter.getBabyParents(map);
                this.showLoading();
                break;
        }
    }

    private AlertDialog alertDialog = null;
    private List<BabyParentsEvent> list = new ArrayList<>();
    private Map<String, BabyParentsEvent> babyMap = new ArrayMap<>();

    public void showMutilAlertDialog(final BabyParentsBean babyParentsBean) {
        if (list.size() > 0) {
            list.clear();
        }
        if (babyMap.size() > 0) {
            babyMap.clear();
        }
        final String[] items = new String[babyParentsBean.getData().size()];
        for (int index = 0; index < babyParentsBean.getData().size(); index++) {
            list.add(new BabyParentsEvent(babyParentsBean.getData().get(index).getId(), babyParentsBean.getData().get(index).getBabyName()));
            items[index] = String.valueOf(babyParentsBean.getData().get(index).getBabyName()) + "家长";
        }

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        /**
         * 第一个参数:弹出框的消息集合，一般为字符串集合
         * 第二个参数：默认被选中的，布尔类数组
         * 第三个参数：勾选事件监听
         */
        alertBuilder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
                String babyId = items[i];
                if (isChecked) {
                    babyMap.put(babyId, list.get(i));
                    Log.e(TAG, "map:" + babyMap.toString());
                } else {
                    babyMap.remove(babyId);
                    Log.e(TAG, "map:" + babyMap.toString());
                }
            }
        });
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                tvSelectName.setText("");
                if (babyMap.size() > 0) {
                    for (String index : babyMap.keySet()) {
                        tvSelectName.setText(tvSelectName.getText().toString() + babyMap.get(index).babyName + "家长,");
                    }
                    String seleteName = tvSelectName.getText().toString();
                    if (seleteName.endsWith(",")) {
                        tvSelectName.setText(seleteName.substring(0, seleteName.length() - 1));
                    }
                } else {
                    ToastUtil.showShortToast(VoteInfromActivity.this, "请选择私信的家长");
                }
                alertDialog.dismiss();
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();
            }
        });
        alertDialog = alertBuilder.create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    /**
     * 跳转到相册页
     */
    private void startCameta() {
        /*Intent picture = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(picture, REQUEST_GET_IMAGE);*/

        Matisse.from(this)
                .choose(MimeType.ofImage(), false) // 选择 mime 的类型
                .countable(true)
                .capture(false)
                .captureStrategy(new CaptureStrategy(true, "com.android.infantschool.fileprovider"))
                .maxSelectable(3) // 图片选择的最多数量
                .gridExpectedSize(ScreenUtil.getWidth() / 3)
                .theme(R.style.Matisse_Dracula)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_GET_IMAGE); // 设置作为标记的请求码
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_GET_IMAGE && resultCode == Activity.RESULT_OK && null != data) {

            //1、第一种方法,系统默认
            List<String> pathList = Matisse.obtainPathResult(data);
            Log.e(TAG, "pathList:" + Arrays.toString(pathList.toArray()));
            for (int index = 0; index < pathList.size(); index++) {
                if (adapter.getItemCount() < 4) {
                    adapter.addData(new ReleaseDynamicBean(pathList.get(index), 1));
                } else {
                    break;
                }
            }
        }
    }

    private Runnable runnable = null;

    /**
     * 上传到七牛
     *
     * @param picUrl
     * @param picSize
     */
    private void qiuNiuYunToKen(final String picUrl, final int picSize) {
        runnable = new Runnable() {
            @Override
            public void run() {
                String qiNiuToken = OkHttpUtil.getmInstance().postSync(AppCommand.QINIU_TOKEN, "token", AppConfig.getToken());
                Log.e(TAG, "qiNiuToken:" + qiNiuToken);
                if (qiNiuToken != null) {
                    QiNiuTokenBean tokenBean = null;
                    try {
                        tokenBean = JsonGet.getGson(qiNiuToken, new QiNiuTokenBean());
                    } catch (Exception e) {
                        tokenBean = null;
                    }
                    if (tokenBean == null) {
                        picNum = 0;
                        flag = true;
                        Log.e(TAG, "上传完毕");

                        String babyId = "";
                        for (String id : babyMap.keySet()) {
                            BabyParentsEvent event = babyMap.get(id);
                            babyId = babyId + event.babyId + ",";
                        }

                        Map<String, String> map = new HashMap<>();
                        map.put("token", AppConfig.getToken());
                        map.put("noticeType", "3");
                        map.put("title", edTitle.getText().toString().trim());
                        map.put("content", edContent.getText().toString().trim());
                        map.put("description", stringBuilder.toString());
                        map.put("babyId", babyId);
                        Log.e(TAG, "map:" + map.toString());
                        presenter.postInfrom(map);
                        return;
                    }
                    if (tokenBean.getCode().equals("0")) {//Token获取成功
                        Log.e(TAG, "qiNiuToken:" + tokenBean.getData().getToken());
                        String ceshitoken = tokenBean.getData().getToken();//请求完接口获取到的token值
                        String key = tokenBean.getData().getKey();
                        Log.e(TAG, "++++++++ceshitoken:" + ceshitoken);
                        // return qiNiuYunBean.getToken();
                        Log.e(TAG, "++++++picNum=" + picNum);
                        Log.e(TAG, "++++++picSize=" + picSize);
                        Log.e(TAG, "++++++picUrl=" + picUrl);

                        QnUploadHelper.uploadPic(picUrl, key, ceshitoken, new QnUploadHelper.UploadCallBack() {
                            @Override
                            public void success(String url) {
                                Log.e(TAG, "上传七牛成功:" + url);
                                picNum++;
                                stringBuilder.append(url + ",");
                                if (picNum < picSize) {
                                    qiuNiuYunToKen((String) adapter.list.get(picNum).path, picSize);
                                } else {
                                    picNum = 0;
                                    flag = true;
                                    Log.e(TAG, "上传完毕");
                                    String babyId = "";
                                    for (String id : babyMap.keySet()) {
                                        BabyParentsEvent event = babyMap.get(id);
                                        babyId = babyId + event.babyId + ",";
                                    }

                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", AppConfig.getToken());
                                    map.put("noticeType", "3");
                                    map.put("title", edTitle.getText().toString().trim());
                                    map.put("content", edContent.getText().toString().trim());
                                    map.put("description", stringBuilder.toString());
                                    map.put("babyId", babyId);
                                    Log.e(TAG, "map:" + map.toString());
                                    presenter.postInfrom(map);
                                    return;
                                }
                            }

                            @Override
                            public void fail(String key, ResponseInfo info) {
                                Log.e(TAG, "上传失败:" + info.error);
                                picNum++;
                                if (picNum < picSize) {
                                    qiuNiuYunToKen((String) adapter.list.get(picNum).path, picSize);
                                } else {
                                    picNum = 0;
                                    flag = true;
                                    Log.e(TAG, "上传完毕");
                                    String babyId = "";
                                    for (String id : babyMap.keySet()) {
                                        BabyParentsEvent event = babyMap.get(id);
                                        babyId = babyId + event.babyId + ",";
                                    }

                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", AppConfig.getToken());
                                    map.put("noticeType", "3");
                                    map.put("title", edTitle.getText().toString().trim());
                                    map.put("content", edContent.getText().toString().trim());
                                    map.put("description", stringBuilder.toString());
                                    map.put("babyId", babyId);
                                    Log.e(TAG, "map:" + map.toString());
                                    presenter.postInfrom(map);
                                    return;
                                }
                            }
                        });
                    } else {
                        Log.e(TAG, "Token获取失败:" + tokenBean.getMsg());
                        final QiNiuTokenBean finalTokenBean = tokenBean;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                picNum = 0;
                                flag = true;
                                VoteInfromActivity.this.dismissLoading();
                                ToastUtil.showShortToast(VoteInfromActivity.this, "Token获取失败:" + finalTokenBean.getMsg());
                            }
                        });
                    }
                } else {
                    Log.e(TAG, "接口异常或网络异常");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            picNum = 0;
                            flag = true;
                            VoteInfromActivity.this.dismissLoading();
                            ToastUtil.showShortToast(VoteInfromActivity.this, "网络异常或接口发生异常");
                        }
                    });
                }
            }
        };
        ThreadPoolManager.getSingleInstance().execute(runnable);
    }

    @Override
    public void imgLister(int position, int type) {
        if (position == (adapter.getItemCount() - 1)) {//去拍照
            startCameta();
        } else {    //去预览
            // TODO: 2019/8/22 去预览
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (flag == false) {
            this.showLoading();
        }
    }

    @Override
    public void errorInfrom(String error) {
        this.dismissLoading();
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successInfrom(BaseBean baseBean) {
        this.dismissLoading();
        ResponseBean responseBean = (ResponseBean) baseBean;
        if (responseBean.getCode() == 0) {
            ToastUtil.showShortToast(this, "发布成功");
            this.finish();
        } else {
            ToastUtil.showShortToast(this, "发布失败:" + responseBean.getMsg());
        }
    }

    @Override
    public void errorBabyParents(String error) {
        this.dismissLoading();
        ToastUtil.showShortToast(this, "网络异常:" + error);
    }

    @Override
    public void successBabyParents(BaseBean baseBean) {
        this.dismissLoading();
        BabyParentsBean parentsBean = (BabyParentsBean) baseBean;
        if (parentsBean.getCode() == 0 && parentsBean.getData() != null) {
            if (parentsBean.getData().size() > 0) {
                showMutilAlertDialog(parentsBean);
            }
        } else {
            ToastUtil.showShortToast(this, "获取失败:" + parentsBean.getMsg());
        }
    }

    @Override
    public void deleteLister(int position, int type) {
        adapter.deleteItem(position);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.onDestroy();
            presenter = null;
        }
        if (parentsPresenter != null) {
            parentsPresenter.onDestroy();
            parentsPresenter = null;
        }
        if (runnable != null) {
            ThreadPoolManager.getSingleInstance().remove(runnable);
        }
    }
}